<?php
/**
 * Created by PhpStorm.
 * User: xiaojun
 * Date: 15/12/22
 * Time: 下午3:08
 */

namespace Home\Controller;
use Common\Controller\BaseController;
use Think\Controller;
class SearchController extends BaseController {

    /**
     * 药品详情入口函数
     */
    public function index(){
        if(!IS_GET){
            $this->error('非法访问');
        }
        //大家都爱搜
        $our_search = F('our_search');
        if(!$our_search || $our_search['expired'] < time()){
            $our_search_info = json_decode($this->http->curl_request(BASE_URL.'search'),true);
            $our_search = $our_search_info['results'];
            $our_search['expired'] = time() + 5*60;
            F('our_search',$our_search);
        }
        //本地搜索历史，放置到session里面
        unset($our_search['expired']);
        $this->assign('our_search',$our_search);
        $this->display('index');
    }

    public function list_search() {
        if(!IS_GET) {
            $this->error('访问非法');
        }
        $value = I('get.value');
        if(empty($value)){
            $this->error('未知的搜索条件');
        }
        $search_type = I('get.access');
        $par['sort_type'] = I('get.sort_type');
        $par['sort_type'] = empty($par['sort_type']) ? 'score' : $par['sort_type'];

        $par['order_type'] = I('get.order_type');
        $par['order_type'] = empty($par['order_type']) ? '-1' : $par['order_type'];

        $par['filter'] = I('get.filter');
        $par['filter'] = empty($par['filter']) ? 'nothing' : $par['filter'];

        $par['p'] = I('get.p');
        $par['p'] = empty($par['p']) ? '1' : $par['p'];

        $par['n'] = I('get.n');
        $par['n'] = empty($par['n']) ? '10' : $par['n'];

        $uri = http_build_query($par);
        $search = json_decode($this->http->curl_request(BASE_URL.'search?'.$uri,['value'=>$value]),true);
        if(isset($search['code'])){
            if($search['code'] == 200){
                if($search_type == 'xhr'){
                    $this->ajaxReturn(['code'=>200,'search'=>$search['results']]);
                }
                $this->assign('search',$search['results']);
                $this->assign('value',$value);
                $this->assign('sort_type',$par['sort_type']);
                $this->assign('order_type',$par['order_type']);
                $this->assign('filter',$par['filter']);
                $this->assign('p',$par['p']);
            }else{
                if($search_type == 'xhr'){
                    $this->ajaxReturn(['code'=>$search['code'],'search'=>$search['message']]);
                }
                $this->assign('search',$search['results']);
            }
        }else{
            if($search_type == 'xhr') {
                $this->ajaxReturn(['code' => 302, 'message' => '没有相关信息']);
            }
            $this->error('没有找到相关信息');
        }
        $this->display('search_list');
    }

    public function test(){
        $this->display('test');
    }

}